/*
 * HSM Proxy Project.
 * Copyright (C) 2013 FedICT.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License version
 * 3.0 as published by the Free Software Foundation.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, see 
 * http://www.gnu.org/licenses/.
 */

package be.fedict.hsm.admin.webapp.security;

import java.security.Principal;
import java.util.Map;

import javax.faces.application.Application;
import javax.faces.application.NavigationHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import be.fedict.hsm.model.security.AdministratorRoles;
import be.fedict.hsm.model.security.SecurityFunction;

@SecurityFunction("SF.I&A.2")
public class SecurityPhaseListener implements PhaseListener {

	private static final long serialVersionUID = 1L;

	private static final String TARGET_VIEW_ID_SESSION_ATTRIBUTE = SecurityPhaseListener.class
			.getName() + ".targetViewId";

	private static final Log LOG = LogFactory
			.getLog(SecurityPhaseListener.class);

	@Override
	public void afterPhase(PhaseEvent phaseEvent) {
		FacesContext facesContext = phaseEvent.getFacesContext();
		UIViewRoot viewRoot = facesContext.getViewRoot();
		String viewId = viewRoot.getViewId();
		LOG.trace("after phase: " + phaseEvent.getPhaseId() + " : " + viewId);
		/*
		 * RESTORE_VIEW and INVOKE_APPLICATION are the most important phases,
		 * but we simply apply the security login to all phases. Notice that
		 * sometimes only at INVOKE_APPLICATION afterPhase you get access to the
		 * new viewId. Hence the need to also do CDI security interception to
		 * prevent unauthorized invocation of the application.
		 * 
		 * The EJB3 security domain on the model is not sufficient as the CDI
		 * components might cache results from the model.
		 */
		if (viewId.startsWith("/admin/")) {
			checkSecurity(facesContext, viewId);
		}
	}

	private void checkSecurity(FacesContext facesContext, String viewId) {
		ExternalContext externalContext = facesContext.getExternalContext();
		Principal userPrincipal = externalContext.getUserPrincipal();
		if (null == userPrincipal) {
			login(facesContext, viewId);
		} else {
			if (false == externalContext
					.isUserInRole(AdministratorRoles.ADMINISTRATOR)) {
				accessDenied(facesContext);
			}
		}
	}

	private void accessDenied(FacesContext facesContext) {
		redirect(facesContext, "/access-denied.xhtml");
	}

	private void login(FacesContext facesContext, String targetViewId) {
		ExternalContext externalContext = facesContext.getExternalContext();
		Map<String, Object> sessionMap = externalContext.getSessionMap();
		sessionMap.put(TARGET_VIEW_ID_SESSION_ATTRIBUTE, targetViewId);
		redirect(facesContext, "/login.xhtml");
	}

	private void redirect(FacesContext facesContext, String viewId) {
		if (facesContext.getResponseComplete()) {
			return;
		}
		Application application = facesContext.getApplication();
		NavigationHandler navigationHandler = application
				.getNavigationHandler();
		navigationHandler.handleNavigation(facesContext, null, viewId
				+ "?faces-redirect=true");
		facesContext.renderResponse();
	}

	@Override
	public void beforePhase(PhaseEvent phaseEvent) {
		FacesContext facesContext = phaseEvent.getFacesContext();
		UIViewRoot viewRoot = facesContext.getViewRoot();
		String viewId;
		if (null == viewRoot) {
			viewId = null;
		} else {
			viewId = viewRoot.getViewId();
		}
		LOG.trace("before phase: " + phaseEvent.getPhaseId() + " : " + viewId);
	}

	@Override
	public PhaseId getPhaseId() {
		return PhaseId.ANY_PHASE;
	}

	public static String getTargetViewId(ExternalContext externalContext) {
		Map<String, Object> sessionMap = externalContext.getSessionMap();
		String targetViewId = (String) sessionMap
				.get(TARGET_VIEW_ID_SESSION_ATTRIBUTE);
		return targetViewId;
	}
}
